<?php
/**
 * Created by PhpStorm
 * User: whh
 * Date: 2022/8/19
 * Time: 9:39
 */

namespace app\backstage\controller;

use app\backstage\facade\UserFacade;
use app\backstage\logic\UserLogic;
use app\backstage\model\ManagerRole;
use app\common\model\Bookshelf;
use app\common\model\QuickUser;
use app\common\model\UserBookPoints;
use app\common\model\UserConsume;
use think\Controller;
use think\Db;
use think\Request;

class User extends Controller
{
    protected $middleware = [
        'VerifyJwt' => ['except' => []],
        'VerifyPower' => ['except' => []],
    ];

    /**
     * 用户列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $role = $request->_role;
        if ($role->alias == 'channel' || $role->alias == 'agent' || $role->alias == 'eb') {
            $this->error('此页面不适合运营角色展示');
        }
        $qas = \app\common\model\QuickApp::getList();
        $this->assign('qas', $qas);

        $agentRole = ManagerRole::getRoleByAlias('agent');
        $where[] = ['role_id', '=', $agentRole['id']];
        $agents = \app\backstage\model\ManagerUser::getList($where);

        $where = [];
        $channelRole = ManagerRole::getRoleByAlias('channel');
        $where[] = ['role_id', '=', $channelRole['id']];
        $channels = \app\backstage\model\ManagerUser::getList($where);

        $where = [];
        $ebRole = ManagerRole::getRoleByAlias('eb');
        $where[] = ['role_id', '=', $ebRole['id']];
        $ebs = \app\backstage\model\ManagerUser::getList($where);

        $this->assign('agents', $agents);
        $this->assign('channels', $channels);
        $this->assign('ebs', $ebs);
        $this->assign('role', $role);
        return $this->fetch();
    }

    /**
     * 读者列表
     * @return \think\response\Json
     * @Author: whh
     */
    public function list()
    {
        $keyword = input('keyword');
        $token = input('token');
        $userId = input('userId');
        $quick_id = input('quick_id');
        $source_agent_id = input('source_agent_id');
        $source_channel_id = input('source_channel_id');
        $source_eb_id = input('source_eb_id');
        $agent_id = input('agent_id');
        $channel_id = input('channel_id');
        $eb_id = input('eb_id');
        $add_shortcut = input('add_shortcut');
        $is_pay = input('is_pay');
        $is_vip = input('is_vip');
        $have_phone = input('have_phone');

        $page = input('page', 1);
        $limit = input('limit', 20);

        $where = [];
        if ($keyword != '') {
            $where[] = ['id|phone', '=', $keyword];
        }
        if ($token != '') {
            $where[] = ['token', '=', $token];
        }
        if ($userId != '') {
            $where[] = ['device_id', '=', $userId];
        }
        if ($quick_id != '') {
            $where[] = ['quick_id', '=', $quick_id];
        }
        if ($source_agent_id != '') {
            $where[] = ['source_agent_id', '=', $source_agent_id];
        }
        if ($source_channel_id != '') {
            $where[] = ['source_channel_id', '=', $source_channel_id];
        }
        if ($source_eb_id != '') {
            $agentRole = ManagerRole::getRoleByAlias('agent');
            $roleWhere[] = ['role_id', '=', $agentRole['id']];
            $roleWhere[] = ['parent_id', '=', $source_eb_id];
            $agentIds = \app\backstage\model\ManagerUser::where($roleWhere)->column('id');
            $where[] = ['source_agent_id', 'in', $agentIds];
            $where[] = ['source_agent_id', '<>', 0];
        }
        if ($agent_id != '') {
            $where[] = ['agent_id', '=', $agent_id];
        }
        if ($channel_id != '') {
            $where[] = ['channel_id', '=', $channel_id];
        }
        if ($eb_id != '') {
            $agentRole = ManagerRole::getRoleByAlias('agent');
            $roleWhere[] = ['role_id', '=', $agentRole['id']];
            $roleWhere[] = ['parent_id', '=', $eb_id];
            $agentIds = \app\backstage\model\ManagerUser::where($roleWhere)->column('id');
            $where[] = ['agent_id', 'in', $agentIds];
            $where[] = ['agent_id', '<>', 0];
        }
        if ($add_shortcut != '') {
            $where[] = ['add_shortcut', '=', $add_shortcut];
        }
        if ($is_pay != '') {
            if ($is_pay == 1) {
                $where[] = ['pay_times', '<>', 0];
            }
            if ($is_pay == 2) {
                $where[] = ['pay_times', '=', 0];
            }
        }
        if ($is_vip != '') {
            $time = time();
            if ($is_vip == 1) {
                $where[] = ['vip_exp_time', '>', $time];
            }
            if ($is_vip == 2) {
                $where[] = ['vip_exp_time', '<', $time];
            }
        }
        if ($have_phone != '') {
            if ($have_phone == 1) {
                $where[] = ['phone', '<>', ''];
            }
            if ($have_phone == 2) {
                $where[] = ['phone', '=', ''];
            }
        }
        $data = UserFacade::userList($where, $page, $limit);
        return $data;
    }


    /**
     * 读者详情
     * @return mixed
     * @Author: whh
     */
    public function info()
    {
        $id = input('id');
        $user = QuickUser::get($id);
        if (!$user) {
            echo "用户不存在";
            die;
        }

        $diff = intval(substr($user->source_quick_id,-2));

        $user->nickname = Db::table('quick_user_'.$diff)->where('id',$user->id)->value('nickname');

        $this->assign('user', $user);
        $ubp = new UserBookPoints();
        $bp = $ubp->getBalancePoint($user->id);
        $this->assign('bp', $bp);
        //累计消耗书币和书点
        $userConsume = new UserConsume();
        $consume = $userConsume->getByUid($id);
        $this->assign('consume', $consume);
        $this->assign('month', date("Ym"));
        $role = \request()->_role;
        $this->assign('role', $role);
        return $this->fetch();
    }


    /**
     * 修改审核状态
     * @return \think\response\Json
     * @Author: whh
     */
    public function changeReviewType()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\UserValidate.changeReviewType');
        if (true !== $result) {
            $this->error($result);
        }
        $res = UserFacade::setReview($params['uid'], $params['type'], 'backstage');
        return $res;
    }


    /**
     * 设置黑白名单
     * @Author: whh
     */
    public function cutBlackOrWhite()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\UserValidate.cutBlackOrWhite');
        if (true !== $result) {
            $this->error($result);
        }
        if ($params['table_suffix'] == 'white') {
            $user = QuickUser::get($params['uid']);
            if ($user->device_id == '36cecec57756f3d27') {
                $this->error('开发用户不允许加白（开发用户会被vivo登陆）');
            }
        }
        UserFacade::setBlackOrWhite($params['table_suffix'], $params['type'], $params['uid']);
        $this->success();
    }


    /**
     * 读者
     * @return mixed
     */
    public function readers()
    {
        $role = \request()->_role;
        $user = \request()->_user;
        if ($role->alias == 'channel' || $role->alias == 'agent' || $role->alias == 'eb') {
            $qas = $user->apps;
        } else {
            $qas = \app\common\model\QuickApp::getList();
        }
        $this->assign('qas', $qas);

        $agents = [];
        $channels = [];
        if ($role->alias == 'eb') {
            /**
             * 商务
             */
            $agentRole = ManagerRole::getRoleByAlias('agent');
            $where[] = ['role_id', '=', $agentRole['id']];
            $where[] = ['parent_id', '=', $user->id];
            $agents = \app\backstage\model\ManagerUser::getList($where);
            $this->assign('agents', $agents);

            $agentIds = $agents ? array_column($agents->toArray(), 'id') : [];
            $where = [];
            $channelRole = ManagerRole::getRoleByAlias('channel');
            $where[] = ['role_id', '=', $channelRole['id']];
            $where[] = ['parent_id', 'in', $agentIds];
            $where[] = ['parent_id', '<>', 0];
            $channels = \app\backstage\model\ManagerUser::getList($where);
        } elseif ($role->alias == 'agent') {
            /**
             * 代理
             */
            $where = [];
            $channelRole = ManagerRole::getRoleByAlias('channel');
            $where[] = ['role_id', '=', $channelRole['id']];
            $where[] = ['parent_id', '=', $user->id];
            $channels = \app\backstage\model\ManagerUser::getList($where);
        }

        $this->assign('agents', $agents);
        $this->assign('channels', $channels);
        $this->assign('role', $role);
        return $this->fetch();
    }

    /**
     * 可运营读者
     * @return mixed
     */
    public function operateUsers()
    {
        $keyword = input('keyword');
        $quick_id = input('quick_id');
        $agent_id = input('agent_id');
        $channel_id = input('channel_id');
        $add_shortcut = input('add_shortcut');
        $is_pay = input('is_pay');
        $is_vip = input('is_vip');
        $have_phone = input('have_phone');
        $is_register = input('is_register');

        $page = input('page', 1);
        $limit = input('limit', 20);

        $where = [];
        if ($keyword != '') {
            $where[] = ['id|phone', '=', $keyword];
        }
        if ($quick_id != '') {
            $where[] = ['quick_id', '=', $quick_id];
        }
        if ($agent_id != '') {
            $where[] = ['agent_id', '=', $agent_id];
        }
        if ($channel_id != '') {
            $where[] = ['channel_id', '=', $channel_id];
        }
        if ($add_shortcut != '') {
            $where[] = ['add_shortcut', '=', $add_shortcut];
        }
        if ($is_pay != '') {
            if ($is_pay == 1) {
                $where[] = ['pay_times', '<>', 0];
            }
            if ($is_pay == 2) {
                $where[] = ['pay_times', '=', 0];
            }
        }
        if ($is_vip != '') {
            $time = time();
            if ($is_vip == 1) {
                $where[] = ['vip_exp_time', '>', $time];
            }
            if ($is_vip == 2) {
                $where[] = ['vip_exp_time', '<', $time];
            }
        }
        if ($have_phone != '') {
            if ($have_phone == 1) {
                $where[] = ['phone', '<>', ''];
            }
            if ($have_phone == 2) {
                $where[] = ['phone', '=', ''];
            }
        }
        if ($is_register != '') {
            $role = request()->_role;
            $user = request()->_user;
            if ($is_register == 1) {
                if ($role->alias == 'channel') {
                    $where[] = ['source_channel_id', '=', $user->id];
                }
                if ($role->alias == 'agent') {
                    $where[] = ['source_agent_id', '=', $user->id];
                }
                if ($role->alias == 'eb') {
                    $userModel = new \app\backstage\model\ManagerUser();
                    $userIds = $userModel->sonUsersIds($user->id);
                    $where[] = ['source_agent_id', 'in', $userIds];
                    $where[] = ['source_agent_id', '<>', 0];
                }
            }
            if ($is_register == 2) {
                if ($role->alias == 'channel') {
                    $where[] = ['source_channel_id', '<>', $user->id];
                }
                if ($role->alias == 'agent') {
                    $where[] = ['source_agent_id', '<>', $user->id];
                }
                if ($role->alias == 'eb') {
                    $userModel = new \app\backstage\model\ManagerUser();
                    $userIds = $userModel->sonUsersIds($user->id);
                    $where[] = ['source_agent_id', 'not in', $userIds];
                }
            }
        }
        $logic = new UserLogic();
        $data = $logic->readersList($where, 'operate', $page, $limit);
        return $data;
    }

    /**
     * 注册用户
     * @return \think\response\Json
     */
    public function registerUsers()
    {
        $keyword = input('keyword');
        $quick_id = input('quick_id');
        $source_agent_id = input('source_agent_id');
        $source_channel_id = input('source_channel_id');
        $add_shortcut = input('add_shortcut');
        $is_pay = input('is_pay');
        $is_vip = input('is_vip');
        $have_phone = input('have_phone');
        $is_belong = input('is_belong');

        $page = input('page', 1);
        $limit = input('limit', 20);

        $where = [];
        if ($keyword != '') {
            $where[] = ['id|phone', '=', $keyword];
        }
        if ($quick_id != '') {
            $where[] = ['quick_id', '=', $quick_id];
        }
        if ($source_agent_id != '') {
            $where[] = ['source_agent_id', '=', $source_agent_id];
        }
        if ($source_channel_id != '') {
            $where[] = ['source_channel_id', '=', $source_channel_id];
        }
        if ($add_shortcut != '') {
            $where[] = ['add_shortcut', '=', $add_shortcut];
        }
        if ($is_pay != '') {
            if ($is_pay == 1) {
                $where[] = ['pay_times', '<>', 0];
            }
            if ($is_pay == 2) {
                $where[] = ['pay_times', '=', 0];
            }
        }
        if ($is_vip != '') {
            $time = time();
            if ($is_vip == 1) {
                $where[] = ['vip_exp_time', '>', $time];
            }
            if ($is_vip == 2) {
                $where[] = ['vip_exp_time', '<', $time];
            }
        }
        if ($have_phone != '') {
            if ($have_phone == 1) {
                $where[] = ['phone', '<>', ''];
            }
            if ($have_phone == 2) {
                $where[] = ['phone', '=', ''];
            }
        }

        if ($is_belong != '') {
            $role = request()->_role;
            $user = request()->_user;
            if ($is_belong == 1) {
                if ($role->alias == 'channel') {
                    $where[] = ['channel_id', '=', $user->id];
                }
                if ($role->alias == 'agent') {
                    $where[] = ['agent_id', '=', $user->id];
                }
                if ($role->alias == 'eb') {
                    $userModel = new \app\backstage\model\ManagerUser();
                    $userIds = $userModel->sonUsersIds($user->id);
                    $where[] = ['agent_id', 'in', $userIds];
                    $where[] = ['agent_id', '<>', 0];
                }
            }
            if ($is_belong == 2) {
                if ($role->alias == 'channel') {
                    $where[] = ['channel_id', '<>', $user->id];
                }
                if ($role->alias == 'agent') {
                    $where[] = ['agent_id', '<>', $user->id];
                }
                if ($role->alias == 'eb') {
                    $userModel = new \app\backstage\model\ManagerUser();
                    $userIds = $userModel->sonUsersIds($user->id);
                    $where[] = ['agent_id', 'not in', $userIds];
                }
            }
        }
        $logic = new UserLogic();
        $data = $logic->readersList($where, 'register', $page, $limit);
        return $data;
    }


    /**
     * 用户阅读记录明细
     * @return \think\response\Json
     */
    public function readRecordDetail()
    {
        $uid = input('uid');
        $month = input('month', date("Ym"));
        $novel_id = input('novel_id');
        $chapter_no = input('chapter_no');
        $pay_read = input('pay_read');
        $page = input('page', 1);
        $limit = input('limit', 10);
        if (!$uid) {
            return errJson('参数异常');
        }
        $where[] = ['uid', '=', $uid];
        if ($novel_id != '') {
            $where[] = ['novel_id', '=', $novel_id];
        }
        if ($chapter_no != '') {
            $where[] = ['chapter_no', '=', $chapter_no];
        }
        if ($pay_read != '') {
            $where[] = ['pay_read', '=', $pay_read];
        }
        return UserFacade::readRecordDetailList($month, $where, $page, $limit);
    }


    /**
     * 领取记录
     * @return \think\response\Json
     */
    public function receiveRecord()
    {
        $uid = input('uid');
        $give_type = input('give_type');
        $is_overdue = input('is_overdue');
        $is_expire = input('is_expire');
        $page = input('page', 1);
        $limit = input('limit', 10);
        if (!$uid) {
            return errJson('参数异常');
        }
        $where[] = ['uid', '=', $uid];
        if ($give_type != '') {
            $where[] = ['give_type', '=', $give_type];
        }
        if ($is_overdue != '') {
            if ($is_overdue == 1) {
                $where[] = ['overdue_time', '<', time()];
            }
            if ($is_overdue == 0) {
                $where[] = ['overdue_time', '>', time()];
            }
        }
        if ($is_expire != '') {
            $where[] = ['is_expire', '=', $is_expire];
        }
        return UserFacade::giveList($where, $page, $limit);
    }

    /*用户充值*/
    public function recharge()
    {
        if( \think\facade\Request::isGet() ){

            return $this->fetch();
        }

        $params = \think\facade\Request::post('','','strip_tags,trim');

        if( !(isset($params['uid']) && $params['uid'] > 0) )
        {
            return json(['code'=>101,'msg'=>'用户ID不能为空']);
        }

        if($params['type'] == 2 && $params['vipdays'] == 0 )
        {
            return json(['code'=>101,'msg'=>'会员天数不能为0']);
        }

        $User = \think\facade\App::model('UserLogic','logic');

        $result = $User->recharge($params);

        return json($result);
    }

    /**
     * 用户刷新
     */
    public function refreshUser(){
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\UserValidate.refreshUser');
        if (true !== $result) {
            $this->error($result);
        }
        $uid = input('uid');
        $user = QuickUser::get($uid);
        if (!$user) {
            $this->error('用户不存在');
        }
        $user->userId = $user->userId . "_ref".rand(10,10000);
        $user->token = $user->token . "_ref".rand(10,10000);
        $user->save();
        Db::table(QuickUser::fbTable($user->quick_id))->where('id', $uid)->update(['userId' => $user->userId, 'token' => $user->token]);
        $this->success();
    }

    public function bookshelf()
    {
        $uid = input('uid');
        $page = input('page', 1);
        $limit = input('limit', 10);
        if (!$uid) {
            $this->error('请输入用户id');
        }
        $where[] = ['uid', '=', $uid];
        $list = Bookshelf::where($where)->with(['novel'])->page($page, $limit)->order("read_time desc")->select();
        $count = Bookshelf::where($where)->count();
        return sucJson($list,$count);
    }
}